/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 表单管理模块
 * 尊重劳动成果是一种美德
 */

let currentSchemas = [];
let editingSchemaIndex = -1;
let currentEditingTokenIndex = -1;
let currentPage = 1;
let pageSize = 10;

// 页面加载后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 监听TAB切换
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                const target = mutation.target;
                if (target.id === 'schema-manage' && target.classList.contains('active')) {
                    loadSchemaList();
                }
            }
        });
    });
    
    const schemaManageTab = document.getElementById('schema-manage');
    if (schemaManageTab) {
        observer.observe(schemaManageTab, { attributes: true });
    }
    
    // 如果表单管理TAB已经激活，直接加载
    if (schemaManageTab && schemaManageTab.classList.contains('active')) {
        setTimeout(loadSchemaList, 500);
    }
});

// 加载表单列表
function loadSchemaList() {
    fetch('api/get_schemas.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentSchemas = data.schemas || [];
                currentPage = 1; // 重置到第一页
                displaySchemaList();
            }
        })
        .catch(error => {});
}

// 显示表单列表
function displaySchemaList(schemas) {
    const listDiv = document.getElementById('schema-list');
    if (!listDiv) return;
    
    // 如果传入了 schemas 参数，更新 currentSchemas
    if (schemas) {
        currentSchemas = schemas;
    }
    
    if (currentSchemas.length === 0) {
        listDiv.innerHTML = '<div class="no-data">暂无表单，请点击"新增表单"添加</div>';
        document.getElementById('schema-pagination').style.display = 'none';
        return;
    }
    
    // 计算分页
    const totalPages = Math.ceil(currentSchemas.length / pageSize);
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, currentSchemas.length);
    const pageSchemas = currentSchemas.slice(startIndex, endIndex);
    
    let html = `
        <table class="schema-table">
            <thead>
                <tr>
                    <th>名称</th>
                    <th>编码</th>
                    <th>令牌ID</th>
                    <th>令牌密钥</th>
                    <th>类型</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    pageSchemas.forEach((schema, pageIndex) => {
        const actualIndex = startIndex + pageIndex;
        const isDefault = schema.schema_key === 'default';
        const typeBadge = isDefault 
            ? '<span class="schema-badge default">主表单</span>' 
            : '<span class="schema-badge custom">自定义</span>';
        
        const tokenInfo = schema.token_id 
            ? `<span class="token-info">${schema.token_id}</span>` 
            : '<span style="color:var(--color-text-light)">未生成</span>';
        
        const tokenSecret = schema.token_secret
            ? `<span class="token-info">${schema.token_secret}</span>`
            : '<span style="color:var(--color-text-light)">未生成</span>';
        
        html += `
            <tr>
                <td>${escapeHtml(schema.schema_name)}</td>
                <td><code>${escapeHtml(schema.schema_code)}</code></td>
                <td>${tokenInfo}</td>
                <td>${tokenSecret}</td>
                <td>${typeBadge}</td>
                <td>
                    <button class="btn btn-secondary" onclick="editSchema(${actualIndex})">编辑</button>
                    ${!schema.token_id ? '<button class="btn btn-primary" onclick="generateToken('+actualIndex+')">生成</button>' : ''}
                    ${schema.token_id ? '<button class="btn btn-secondary" onclick="manageToken('+actualIndex+')">令牌</button>' : ''}
                </td>
            </tr>
        `;
    });
    
    html += `
            </tbody>
        </table>
    `;
    
    listDiv.innerHTML = html;
    
    // 显示分页
    if (totalPages > 1) {
        displayPagination(totalPages);
    } else {
        document.getElementById('schema-pagination').style.display = 'none';
    }
}

// 显示分页
function displayPagination(totalPages) {
    const paginationDiv = document.getElementById('schema-pagination');
    if (!paginationDiv) return;
    
    let html = '<div class="pagination-controls">';
    
    // 上一页
    if (currentPage > 1) {
        html += `<button class="btn btn-secondary" onclick="goToPage(${currentPage - 1})">上一页</button>`;
    }
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (i === currentPage) {
            html += `<button class="btn btn-primary" disabled>${i}</button>`;
        } else if (i === 1 || i === totalPages || Math.abs(i - currentPage) <= 2) {
            html += `<button class="btn btn-secondary" onclick="goToPage(${i})>${i}</button>`;
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            html += '<span>...</span>';
        }
    }
    
    // 下一页
    if (currentPage < totalPages) {
        html += `<button class="btn btn-secondary" onclick="goToPage(${currentPage + 1})">下一页</button>`;
    }
    
    html += '</div>';
    paginationDiv.innerHTML = html;
    paginationDiv.style.display = 'block';
}

// 跳转到指定页
function goToPage(page) {
    currentPage = page;
    displaySchemaList();
}

// 显示新增表单模态框
function showAddSchemaModal() {
    editingSchemaIndex = -1;
    document.getElementById('schemaModalTitle').textContent = '新增表单';
    document.getElementById('schema-index').value = '';
    document.getElementById('schema-name').value = '';
    document.getElementById('schema-code').value = '';
    document.getElementById('schema-image-fields').value = '';
    document.getElementById('schema-attachment-fields').value = '';
    
    // 新增时隐藏删除按钮
    const deleteBtn = document.getElementById('delete-schema-btn');
    if (deleteBtn) {
        deleteBtn.style.display = 'none';
    }
    
    document.getElementById('schemaModal').style.display = 'flex';
}

// 编辑表单
function editSchema(index) {
    editingSchemaIndex = index;
    const schema = currentSchemas[index];
    
    document.getElementById('schemaModalTitle').textContent = '编辑表单';
    document.getElementById('schema-index').value = index;
    document.getElementById('schema-name').value = schema.schema_name;
    document.getElementById('schema-code').value = schema.schema_code;
    
    // 图片字段：数组转字符串
    const imageFields = schema.image_fields || [];
    document.getElementById('schema-image-fields').value = Array.isArray(imageFields) ? imageFields.join(',') : imageFields;
    
    // 附件字段：数组转字符串
    const attachmentFields = schema.attachment_fields || [];
    document.getElementById('schema-attachment-fields').value = Array.isArray(attachmentFields) ? attachmentFields.join(',') : attachmentFields;
    
    // 控制删除表单按钮的显示：默认表单不显示删除按钮
    const deleteBtn = document.getElementById('delete-schema-btn');
    if (deleteBtn) {
        const isDefault = schema.schema_key === 'default';
        deleteBtn.style.display = isDefault ? 'none' : 'inline-block';
    }
    
    document.getElementById('schemaModal').style.display = 'flex';
}

// 隐藏表单模态框
function hideSchemaModal() {
    document.getElementById('schemaModal').style.display = 'none';
}

// 保存表单
function saveSchema() {
    const index = document.getElementById('schema-index').value;
    const name = document.getElementById('schema-name').value.trim();
    const code = document.getElementById('schema-code').value.trim();
    const imageFieldsStr = document.getElementById('schema-image-fields').value.trim();
    const attachmentFieldsStr = document.getElementById('schema-attachment-fields').value.trim();
    
    if (!name || !code) {
        alert('表单名称和编码不能为空');
        return;
    }
    
    // 处理图片字段：字符串转数组
    const imageFields = imageFieldsStr ? imageFieldsStr.split(',').map(f => f.trim()).filter(f => f) : [];
    
    // 处理附件字段：字符串转数组
    const attachmentFields = attachmentFieldsStr ? attachmentFieldsStr.split(',').map(f => f.trim()).filter(f => f) : [];
    
    const formData = new FormData();
    formData.append('action', index === '' ? 'add' : 'update');
    if (index !== '') formData.append('index', index);
    formData.append('schema_name', name);
    formData.append('schema_code', code);
    formData.append('image_fields', JSON.stringify(imageFields));
    formData.append('attachment_fields', JSON.stringify(attachmentFields));
    
    fetch('api/save_schema.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Toast.success(index === '' ? '表单添加成功' : '表单修改成功');
            hideSchemaModal();
            loadSchemaList();
        } else {
            Toast.error('保存失败: ' + data.message);
        }
    })
    .catch(error => {
        Toast.error('保存异常: ' + error.message);
    });
}

// 删除当前表单（从弹窗中调用）
function deleteCurrentSchema() {
    const index = document.getElementById('schema-index').value;
    if (index === '') {
        Toast.error('无法删除：未找到表单索引');
        return;
    }
    
    const schema = currentSchemas[index];
    
    if (!confirm(`确定要删除表单"${schema.schema_name}"吗？`)) {
        return;
    }
    
    deleteSchema(index);
    hideSchemaModal();
}

// 删除表单
function deleteSchema(index) {
    const schema = currentSchemas[index];
    
    if (!confirm(`确定要删除表单"${schema.schema_name}"吗？`)) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'delete');
    formData.append('index', index);
    
    fetch('api/save_schema.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Toast.success('表单删除成功');
            loadSchemaList();
        } else {
            Toast.error('删除失败: ' + data.message);
        }
    })
    .catch(error => {
        Toast.error('删除异常: ' + error.message);
    });
}

// 生成或查看令牌
function generateToken(index) {
    const schema = currentSchemas[index];
    
    // 如果已有令牌，直接显示
    if (schema.token_id && schema.token_secret) {
        viewToken(index);
        return;
    }
    
    // 生成新令牌
    const formData = new FormData();
    formData.append('action', 'generate_token');
    formData.append('index', index);
    
    fetch('api/save_schema.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Toast.success('令牌生成成功');
            loadSchemaList();
            showTokenInfo(data.token_id, data.token_secret);
        } else {
            Toast.error('生成令牌失败: ' + data.message);
        }
    })
    .catch(error => {
        Toast.error('生成令牌异常: ' + error.message);
    });
}

// 管理令牌（查看+编辑）
function manageToken(index) {
    const schema = currentSchemas[index];
    currentEditingTokenIndex = index;
    
    if (schema.token_id && schema.token_secret) {
        showTokenManageModal(schema.token_id, schema.token_secret, index);
        
        // 控制删除令牌按钮的显示：默认表单不显示删除按钮
        const deleteBtn = document.getElementById('delete-token-btn');
        if (deleteBtn) {
            const isDefault = schema.schema_key === 'default';
            deleteBtn.style.display = isDefault ? 'none' : 'inline-block';
        }
    }
}

// 显示令牌管理模态框
function showTokenManageModal(tokenId, tokenSecret, index) {
    document.getElementById('display-token-id').value = tokenId;
    document.getElementById('display-token-secret').value = tokenSecret;
    
    // 保存当前编辑的索引
    document.getElementById('tokenModal').setAttribute('data-index', index);
    
    document.getElementById('tokenModal').style.display = 'flex';
}

// 随机生成令牌ID - 符合api.php标准：9位大小写字母+数字
function regenerateTokenId() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let tokenId = '';
    for (let i = 0; i < 9; i++) {
        tokenId += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    
    document.getElementById('display-token-id').value = tokenId;
}

// 随机生成令牌密钥 - 符合api.php标准：24位大小写字母+数字
function regenerateTokenSecret() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let tokenSecret = '';
    for (let i = 0; i < 24; i++) {
        tokenSecret += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    
    document.getElementById('display-token-secret').value = tokenSecret;
}

// 保存令牌修改
function saveTokenChanges() {
    const tokenModal = document.getElementById('tokenModal');
    const index = tokenModal.getAttribute('data-index');
    
    const newTokenId = document.getElementById('display-token-id').value.trim();
    const newTokenSecret = document.getElementById('display-token-secret').value.trim();
    
    if (!newTokenId || !newTokenSecret) {
        alert('令牌ID和密钥不能为空');
        return;
    }
    
    // 验证 token_secret 长度：24位
    if (newTokenSecret.length !== 24) {
        alert('令牌密钥必须为24位（当前: ' + newTokenSecret.length + '位）');
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'edit_token');
    formData.append('index', index);
    formData.append('token_id', newTokenId);
    formData.append('token_secret', newTokenSecret);
    
    fetch('api/save_schema.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Toast.success('令牌保存成功');
            hideTokenModal();
            loadSchemaList();
        } else {
            Toast.error('保存令牌失败: ' + data.message);
        }
    })
    .catch(error => {
        Toast.error('保存令牌异常: ' + error.message);
    });
}

// 删除当前令牌（从弹窗中调用）
function deleteCurrentToken() {
    if (currentEditingTokenIndex >= 0) {
        const schema = currentSchemas[currentEditingTokenIndex];
        
        if (!confirm(`确定要删除表单"${schema.schema_name}"的令牌吗？`)) {
            return;
        }
        
        deleteToken(currentEditingTokenIndex);
        hideTokenModal();
    }
}

// 删除令牌
function deleteToken(index) {
    const schema = currentSchemas[index];
    
    if (!confirm(`确定要删除表单“${schema.schema_name}”的令牌吗？`)) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'delete_token');
    formData.append('index', index);
    
    fetch('api/save_schema.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Toast.success('令牌删除成功');
            loadSchemaList();
        } else {
            Toast.error('删除令牌失败: ' + data.message);
        }
    })
    .catch(error => {
        Toast.error('删除令牌异常: ' + error.message);
    });
}

// 显示令牌信息
function showTokenInfo(tokenId, tokenSecret) {
    document.getElementById('display-token-id').value = tokenId;
    document.getElementById('display-token-secret').value = tokenSecret;
    document.getElementById('tokenModal').style.display = 'flex';
}

// 隐藏令牌模态框
function hideTokenModal() {
    document.getElementById('tokenModal').style.display = 'none';
}

// 复制到剪贴板
function copyToClipboard(elementId) {
    const element = document.getElementById(elementId);
    element.select();
    document.execCommand('copy');
    
    Toast.success('已复制到剪贴板');
}

// 更新状态显示
function updateSchemaStatus(message, type) {
    const statusElement = document.getElementById('schema-status');
    if (statusElement) {
        statusElement.textContent = message;
        statusElement.className = 'schema-status ' + type;
        statusElement.style.display = 'block';
        
        // 3秒后自动隐藏成功状态
        if (type === 'success') {
            setTimeout(() => {
                statusElement.style.display = 'none';
            }, 3000);
        }
    }
}

// 转义HTML
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}
